package com.competitions.videoedithelper.service.impl;

import com.competitions.videoedithelper.dao.NewVideoDao;
import com.competitions.videoedithelper.entity.NewVideo;
import com.competitions.videoedithelper.entity.ResponseModel;
import com.competitions.videoedithelper.entity.VideoInfo;
import com.competitions.videoedithelper.service.NewVideoService;
import com.competitions.videoedithelper.utils.PageUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * @author 盛旭雯
 */
@Service
public class NewVideoServiceImpl implements NewVideoService {
    private NewVideoDao newVideoDao;

    @Autowired
    public NewVideoServiceImpl(NewVideoDao newVideoDao) {
        this.newVideoDao = newVideoDao;
    }

    @Override
    public void selectVideos(HttpServletResponse resp, int videoId, int pageNum, int pageSize) {
        try {
            List<Map<String,Object>> list= newVideoDao.selectVideos(videoId);
            try {
                JSONObject jsonObject = PageUtil.wrap(list,"Video",pageSize,pageNum);
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWriter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWriter.append(jsonObject.toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public ResponseModel selectVideo(int videoId) {
        try {
            NewVideo newVideo=newVideoDao.selectVideo(videoId);
            return new ResponseModel(200,"查找成功",newVideo);
        }catch (Exception e){
            return new ResponseModel(174,"查找失败");
        }
    }

    @Override
    public ResponseModel deleteVideo(int videoId) {
        NewVideo newVideo=newVideoDao.selectVideo(videoId);
        File file = new File(newVideo.getFilePath());
        if(file.delete()) {
            newVideoDao.deleteVideo(videoId);
            return new ResponseModel(200,"删除成功");
        }
        return new ResponseModel(199,"删除失败");
    }
}
